import { Breadcrumb, Button, Card, Form, Radio,DatePicker, Table, Tag, Space, message, Modal } from 'antd';
import { Link } from 'react-router-dom';
import React, { useEffect, useRef, useState } from 'react'
import { EditOutlined,DeleteOutlined} from '@ant-design/icons';
// import { getChannelsAPI } from 'api/channel';
import { delArticlesByIdAPI, getArticlesAPI } from 'api/article';
import errorSrc from 'assets/error.png'
import Channel from "components/Channel"
import { useHistory } from 'react-router-dom';
// const { Option } = Select;
const { RangePicker } = DatePicker
export default function ArticleList() {
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ]
  //获取history
  const history = useHistory()
  
  //声明变量保存文章列表数据
  let [articleData, setArticleData] = useState({})
  
  //获取文章列表封装函数
  const loadArticles=async (params={})=>{
    const res = await getArticlesAPI(params)
    setArticleData(res.data)
  }
  //挂载后发送请求获取频道列表
  useEffect(()=>{
    loadArticles()
  },[])
  //  创建ref用于存储筛选数据
  const refFormData = useRef()
  //创建ref用于存储分页数据
  const pageInfoRef = useRef()
  // Form表单验证收集信息
  const handleSubmit =(values) => { 
     let formData = {...values}
     //转换status字段数据
     if(values.status===-1) delete formData.status
    //  转换date字段数据
     if(values.date){
       const startTime = values.date[0].startOf('day').format('YYYY-MM-DD HH-mm-ss')
       const endTime = values.date[1].endOf('day').format('YYYY-MM-DD HH-mm-ss')
       formData.begin_pubdate= startTime
       formData.end_pubdate=endTime
       delete formData.date
      }
      // 调用ref.current存储formData,用于分页器传值
      refFormData.current=formData
      loadArticles(formData)
   }
   //分页器onChange事件
   const handleChange=(page, per_page)=>{
     //存储分页数据
     pageInfoRef.current={page,per_page}
    //  调用文章列表封装函数传入分页数值条件和ref筛选条件
    loadArticles({page,per_page,...(refFormData.current||{})})
   }
   //删除点击事件
   const handleDelById=(id)=>{
     //二次询问用户
     Modal.confirm({
       title:"注意啦!!!!",
       content:"你要删除?!",
      //  onOk接收一个回调函数,可以改为异步函数
       onOk:async()=>{
         await delArticlesByIdAPI(id)
         // 结构refFormData和pageInfoRef
         const formData=refFormData.current||{}
         const pageInfoData=pageInfoRef.current||{}
         //调用删除文章接口传入筛选条件formData和分页数值pageInfoData
         await loadArticles({...formData,...pageInfoData})
         message.success('删除成功',1)
       }
     })
   }
   //表格组件配置列
   const columns =[
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value)=> {
        //处理空图片设置默认图片
        if(!value.images.length){
          return <img width={100} height={60} src={errorSrc} alt="" />
        }
        return <img width={100} height={60} src={value.images[0]} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value)=> {
        // console.log('value  ----->  ', value);
        const info = articleStatus.find((item)=>item.id===value)
        // console.log('info  ----->  ', info);
        return <Tag color={info.color}>{info.name}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key:"action",
      //record代表整行数据
      render: (value,record)=> {
        return (
         <Space>
            {/* 1. 添加click事件 */}
            {/* 2. 跳转路由，记得传参id */}
           <Button type="primary" shape="circle" icon={<EditOutlined />} size='small'  onClick={() => history.push('/edit/' + record.id)} />
           <Button  danger shape="circle" icon={<DeleteOutlined />} size='small' onClick={()=>handleDelById(record.id)} />
         </Space> 
        )  
      }
    }
   ]
  return (
    <div style={{paddingTop:24}}>
      <Card title={
      <Breadcrumb>
           <Breadcrumb.Item>
               <Link to='/home'>首页</Link>
           </Breadcrumb.Item>  
           <Breadcrumb.Item>
               <Breadcrumb.Item>文章列表</Breadcrumb.Item>
           </Breadcrumb.Item>
      </Breadcrumb>
      } bordered={false}>
      <Form autoComplete="off" onFinish={handleSubmit} initialValues={{status:-1,channel_id:0}}>
        <Form.Item label="状态" name="status">
          {/* 单选框 */}
           <Radio.Group >
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
           </Radio.Group>
        </Form.Item>
         {/* 调用封装组件方式显示下拉选择框 */}
        <Form.Item label="频道" name="channel_id">
          <Channel style={{ width: 200 }}></Channel>
        </Form.Item>

           {/* 日期选择框 */}
        <Form.Item label="日期" name="date"> 
            <RangePicker />
        </Form.Item>

        {/* 筛选按钮 */}
        <Form.Item>
            <Button type="primary" htmlType="submit">
               筛选
            </Button>
        </Form.Item>
      </Form>
      {/* 显示数据总量 */}
      根据筛选条件共查询到{articleData.total_count}条结果
      {/* 表格 */}
      <Table columns={columns} dataSource={articleData.results} rowKey='id' pagination={{
        current:articleData.page,
        pageSize:articleData.per_page,
        total:articleData.total_count,
        position:["bottomCenter"],
        onChange:handleChange
        }}/>
       </Card>
    </div>
  );
}

